package club.ruanx.auth.vcode.controller;

import club.ruanx.auth.vcode.enumeration.ValidateCodeType;
import club.ruanx.auth.vcode.factory.ValidateCodeProcessor;
import club.ruanx.auth.vcode.factory.ValidateCodeProcessorManager;
import club.ruanx.security.util.ResponseUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 阮胜
 * @date 2018/9/30 13:37
 */
@RestController
@RequestMapping("/validate/code")
@Slf4j
public class ValidateCodeController {

    private final ValidateCodeProcessorManager validateCodeProcessorManager;

    public ValidateCodeController(ValidateCodeProcessorManager validateCodeProcessorManager) {
        this.validateCodeProcessorManager = validateCodeProcessorManager;
    }

    /**
     * 创建验证码，根据验证码类型不同，调用不同的 {@link ValidateCodeProcessor}接口实现
     *
     * @param resp
     * @param type
     */
    @GetMapping("/{type}")
    public void createValidateCode(HttpServletResponse resp, @PathVariable String type) throws IOException {


        ValidateCodeType validateCodeType;
        try {
            validateCodeType = ValidateCodeType.valueOf(type.toUpperCase());
        } catch (Exception e) {
            log.info(e.getMessage());
            ResponseUtils.sendMessage(resp, false, "错误的验证码类型");
            return;
        }
        validateCodeProcessorManager.findValidateCodeProcessor(type).create(validateCodeType);
    }
}
